//
//  BDShopSearchViewController.m
//  iOS_beboy
//
//  Created by wen on 2017/11/14.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDShopSearchViewController.h"
#import "BDSearchResultViewController.h"
#import "UIViewController+BackButtonHandler.h"
#import "BDGeneralCell.h"

@interface BDShopSearchViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, BackButtonHandlerProtocol>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) NSMutableArray *datasource;
@property (nonatomic, copy) void(^keyboardHideBlock)();

@end

@implementation BDShopSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self layoutViews];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide) name:UIKeyboardWillHideNotification object:nil];
}

- (BOOL)navigationShouldPopOnBackButton{
    if ([self.textField isFirstResponder]) {
        __weak BDShopSearchViewController *weakSelf = self;
        _keyboardHideBlock = ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        };
        [self.textField resignFirstResponder];
        return NO;
    }
    return YES;
}

- (void)keyboardDidHide{
    if (_keyboardHideBlock) {
        _keyboardHideBlock();
        _keyboardHideBlock = nil;
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.datasource = [NSMutableArray arrayWithContentsOfFile:[DocumentPath stringByAppendingPathComponent:@"search.plist"]];
    [self resetTableViewFooterView];
    self.tableView.tableHeaderView = [self customHeaderView];
    [self.tableView reloadData];
    [self.textField becomeFirstResponder];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}

- (void)resetTableViewFooterView{
    if (_datasource.count) {
        UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 45)];
        footer.backgroundColor = [UIColor whiteColor];
        
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.image = [UIImage imageNamed:@"shop_deleted.png"];
        imageView.size = CGSizeMake(14, 14);
        
        UILabel *label = [[UILabel alloc] init];
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithHexString:@"#999999"];
        label.text = @"清空历史记录";
        [label sizeToFit];
        label.centerY = footer.height / 2.0;
        label.centerX = footer.width / 2.0 + imageView.width + 5;
        [footer addSubview:label];
        
        imageView.right = label.left - 5;
        imageView.centerY = label.centerY;
        [footer addSubview:imageView];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = footer.bounds;
        [footer addSubview:button];
        
        [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [self.view alertWithTitle:@"提示" message:@"清空历史记录？" type:AlertTypeAlert cancleTitle:@"取消" otherTitle:@[@"确定"] clickBlock:^(NSInteger index) {
                if (index ==1) {
                    //删除
                    [self.datasource removeAllObjects];
                    [self.datasource writeToFile:[DocumentPath stringByAppendingPathComponent:@"search.plist"] atomically:YES];
                    [self.tableView reloadData];
                    [self resetTableViewFooterView];
                }
            }];
        }];
        _tableView.tableFooterView = footer;
    }else{
        UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, kBDScreenHeight)];
        footer.backgroundColor = self.view.backgroundColor;
        
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.image = [UIImage imageNamed:@"container.png"];
        imageView.size = CGSizeMake(kBDScreenWidth - 150, kBDScreenWidth - 150);
        imageView.top = 50;
        imageView.centerX = kBDScreenWidth / 2.0;
        [footer addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] init];
        label.font = [UIFont systemFontOfSize:13];
        label.textColor = [UIColor colorWithHexString:@"#999999"];
        label.text = @"看到我内心的空虚了吗？快帮我填满吧~";
        [label sizeToFit];
        label.centerX = kBDScreenWidth / 2.0;
        label.top = imageView.bottom + 10;
        [footer addSubview:label];
        
        _tableView.tableFooterView = footer;
    }
}

- (void)layoutViews{
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 280 / 375.0 * kBDScreenWidth, 30)];
    _textField.backgroundColor = [UIColor colorWithHexString:@"#555555"];
    _textField.tintColor = [UIColor colorWithHexString:@"#bbbbbb"];
    _textField.font = [UIFont systemFontOfSize:13];
    _textField.placeholder = @"输入商家名称";
    _textField.textColor = [UIColor whiteColor];
    _textField.delegate = self;
    _textField.layer.masksToBounds = YES;
    _textField.layer.cornerRadius = 5;
    _textField.centerX = self.view.width / 2.0 - 10;
    
    [_textField setValue:[UIColor colorWithHexString:@"#bbbbbb"] forKeyPath:@"_placeholderLabel.textColor"];
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 35, 30)];
    leftView.backgroundColor = [UIColor clearColor];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    imageView.image = [UIImage imageNamed:@"search_gray"];
    [leftView addSubview:imageView];
    imageView.right = leftView.width - 5;
    imageView.centerY = leftView.height / 2.0;
    _textField.leftView = leftView;
    _textField.leftViewMode = UITextFieldViewModeAlways;
    self.navigationItem.titleView = _textField;
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchbuttonAction)];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)searchbuttonAction{
    if (self.textField.text.length == 0) {
        [self.view alertWithTitle:@"提示" message:@"没有输入搜索内容" type:AlertTypeAlert cancleTitle:@"确定" otherTitle:nil clickBlock:nil];
    }else{
        __weak BDShopSearchViewController *weakSelf = self;
        _keyboardHideBlock = ^{
            if ([weakSelf.datasource containsObject:weakSelf.textField.text]) {
                [weakSelf.datasource removeObject:weakSelf.textField.text];
            }
            [weakSelf.datasource insertObject:weakSelf.textField.text atIndex:0];
            [weakSelf.datasource writeToFile:[DocumentPath stringByAppendingPathComponent:@"search.plist"] atomically:YES];
            BDSearchResultViewController *resultVC = [[BDSearchResultViewController alloc] init];
            resultVC.keyword = weakSelf.textField.text;
            [weakSelf.navigationController pushViewController:resultVC animated:YES];
        };
        [self.textField resignFirstResponder];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datasource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *string = self.datasource[indexPath.row];
    BDGeneralModel *model = [BDGeneralModel new].titleEqual(string).modeEqual(BDGeneralCellModeButton).imageEqual(@"search_gray.png").imageTypeEqual(BDGeneralCellImageTypeImageName);
    BDGeneralCell *cell = [BDGeneralCell cellForTableView:tableView model:model indexPath:indexPath identifier:@"searchCell"];
    
    cell.subviewBlock = ^(BDGeneralCell *generalCell) {
        generalCell.imageView.size = CGSizeMake(15, 15);
        generalCell.imageView.left = 15;
        generalCell.imageView.centerY = generalCell.height / 2.0;
        
        generalCell.aButton.size = CGSizeMake(10, 10);
        [generalCell.aButton setEnlargeEdgeWithTop:15 right:15 bottom:15 left:15];
        [generalCell.aButton setBackgroundImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
        generalCell.aButton.centerY = generalCell.height / 2.0;
        generalCell.aButton.right = kBDScreenWidth - 15;
        
        generalCell.textLabel.font = [UIFont systemFontOfSize:14];
        generalCell.textLabel.textColor = [UIColor colorWithHexString:@"#333333"];
        [generalCell.textLabel sizeToFit];
        generalCell.textLabel.left = generalCell.imageView.right + 15;
        generalCell.textLabel.centerY = generalCell.height / 2.0;
        generalCell.textLabel.width = MIN(generalCell.textLabel.width, generalCell.aButton.left - 10 - generalCell.textLabel.left);
        
    };
    __weak BDShopSearchViewController *weakSelf = self;
    cell.clickButtonBlock = ^(BDGeneralCell *generalCell) {
        [weakSelf.datasource removeObjectAtIndex:indexPath.row];
        [weakSelf.datasource writeToFile:[DocumentPath stringByAppendingPathComponent:@"search.plist"] atomically:YES];
        [weakSelf.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        [weakSelf resetTableViewFooterView];
    };
    
    return cell;
    
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchCell"];
//    if (cell == nil) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"searchCell"];
//
//        UIButton *deletedButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        deletedButton.size = CGSizeMake(10, 10);
//        [deletedButton setEnlargeEdgeWithTop:15 right:15 bottom:15 left:15];
//        [deletedButton setBackgroundImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
//        [cell.contentView addSubview:deletedButton];
//        deletedButton.centerY = cell.height / 2.0;
//        deletedButton.right = kBDScreenWidth - 15;
//        [[deletedButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
//            [self.datasource removeObjectAtIndex:indexPath.row];
//            [self.datasource writeToFile:[DocumentPath stringByAppendingPathComponent:@"search.plist"] atomically:YES];
//            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//        }];
//
//    }
//    cell.textLabel.text = self.datasource[indexPath.row];
//    cell.textLabel.font = [UIFont systemFontOfSize:14];
//    cell.textLabel.textColor = [UIColor colorWithHexString:@"#4c4c4c"];
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    cell.layer.borderWidth = 0.5;
//    cell.layer.borderColor = kBDColorGray.CGColor;
//    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.textField.text = self.datasource[indexPath.row];
    [self searchbuttonAction];
}

- (UIView *)customHeaderView{
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 94 + 10 + 15 + 6)];
    header.backgroundColor = [UIColor clearColor];
    UILabel *label = [[UILabel alloc] init];
    label.text = @"商家分类";
    label.textColor = [UIColor colorWithHexString:@"#767676"];
    label.font = [UIFont systemFontOfSize:14];
    label.size = CGSizeMake([label.text widthWithFont:label.font], label.font.pointSize+1);
    label.top = 10;
    label.left = 10;
    label.backgroundColor = [UIColor clearColor];
    [header addSubview:label];
    
    UIView *buttonBKView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 80)];
    buttonBKView.top = label.bottom + 5;
    [header addSubview:buttonBKView];
    
    CGFloat buttonWdith = kBDScreenWidth / 3.0;
    CGFloat buttonHeight = 40;
    NSArray *titleArr = @[@"全部",@"桑拿",@"KTV",@"夜总会",@"酒吧",@"沐足"];
    for (int i = 0; i < 6; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(buttonWdith * (i % 3), buttonHeight * (i / 3), buttonWdith, buttonHeight);
        [button setTitle:titleArr[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithHexString:@"#4c4c4c"] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        button.layer.borderColor = kBDColorGray.CGColor;
        button.layer.borderWidth = 0.5;
        button.backgroundColor = [UIColor whiteColor];
        [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            __weak BDShopSearchViewController *weakSelf = self;
            _keyboardHideBlock = ^{
                BDSearchResultViewController *resultVC = [[BDSearchResultViewController alloc] init];
                resultVC.typeNumber = i;
                [weakSelf.navigationController pushViewController:resultVC animated:YES];
            };
            [self.textField resignFirstResponder];
        }];
        [buttonBKView addSubview:button];
    }
    
    UILabel *label1 = [[UILabel alloc] init];
    label1.text = @"搜索历史";
    label1.textColor = [UIColor colorWithHexString:@"#767676"];
    label1.font = [UIFont systemFontOfSize:14];
    label1.size = CGSizeMake([label1.text widthWithFont:label1.font], label1.font.pointSize+1);
    label1.top = buttonBKView.bottom + 15;
    label1.left = 10;
    label1.backgroundColor = [UIColor clearColor];
    [header addSubview:label1];
    header.height = label1.bottom + 10;
    
    return header;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
